package com.dangjian.dangjian_server.controller;

import com.alibaba.fastjson.JSONObject;
import com.dangjian.dangjian_server.common.ResponseMessage;
import com.dangjian.dangjian_server.config.WechatConfig;
import com.dangjian.dangjian_server.dao.StudentDao;
import com.dangjian.dangjian_server.pojo.Student;
import com.dangjian.dangjian_server.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序端 请求
 *
 */
@Slf4j
@RestController
@RequestMapping(value = "wxApi")
public class WxController {
    @Autowired
    private StudentDao studentDao;

    /**
     * 微信登录
     * 获取openId
     * @return
     */
    @GetMapping("wxLogin")
    public ResponseMessage wxLogin(String code){
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", WechatConfig.APP_ID);
        param.put("secret", WechatConfig.APP_SECRET);
        param.put("js_code", code);
        param.put("grant_type", WechatConfig.WX_LOGIN_GRANT_TYPE);

        // 向微信服务端发送请求
        // 发送请求
        String wxResult = HttpClientUtil.doGet(WechatConfig.WX_LOGIN_URL, param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        System.out.println(jsonObject.toString());
        if (jsonObject.containsKey("openid")) {
            //存在openid值，将返回的openid，sessionKey存入map
            Map<String, Object> map = new HashMap<>();
            // 获取参数返回的
            String session_key = jsonObject.get("session_key").toString();
            String open_id = jsonObject.get("openid").toString();
            map.put("openid", open_id);
            map.put("session_key", session_key);
            // 根据openId校验是否存在学生
            Student student = studentDao.selectByOpenId(open_id);

            if (student != null) {
                // 存在 isLoginState==0
                map.put("isLoginState",0);
                map.put("info",student);
                return ResponseMessage.createBySuccess(map);
            } else {
                // 都不是 是游客
                map.put("isLoginState",1);
                map.put("info",null);
                // 返回信息
                return ResponseMessage.createBySuccess(map);
            }
        } else {
            return ResponseMessage.createByErrorMessage(jsonObject.get("errmsg").toString());
        }
    }
}
